<template>
  <div class="app-container v-flex">
    <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
    <div ref="main" class="v-flex-elastic">
      <el-table
        v-if="height>0"
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        border
        :height="height"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column prop="parameterType" show-overflow-tooltip label="配置类型" />
        <el-table-column prop="parameterName" show-overflow-tooltip label="配置名称" />
        <el-table-column prop="parameterCode" show-overflow-tooltip label="配置编号" />
        <el-table-column prop="parameterValue" show-overflow-tooltip label="配置值" />
        <el-table-column prop="memo" show-overflow-tooltip label="描述" />
        <el-table-column label="启用" align="center" width="70">
          <template slot-scope="{row, $index}">
            <el-switch v-model="row.status" @change="enable(row, $index)" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="120"
          class-name="small-padding fixed-width">
          <template slot-scope="{row ,$index}">
            <el-button
              v-permission-button="'ITPS-VIEW'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-view"
              @click="view(row)" />
            <el-button
              v-permission-button="'ITPS-UPDATE'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-edit"
              @click="updateForm(row,$index)" />
            <el-button
              v-permission-button="'ITPS-DELETE'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-delete"
              @click="deleteData(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-box">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getListPage" />
    </div>

    <base-dialog
      class="config-dialog"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @updateData="updateData">
      <el-form ref="dataForm" :rules="rules" :model="temp" :disabled="dialog.disabled" label-width="85px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="parameterName">
              <el-input v-model="temp.parameterName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置类型" prop="parameterType">
              <el-select v-model="temp.parameterType" filterable allow-create>
                <el-option v-for="item in option" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置编号" prop="parameterCode">
              <el-input v-if="dialogStatus == 'update'" v-model="temp.parameterCode" disabled />
              <el-input v-else v-model="temp.parameterCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置值" prop="parameterValue">
              <el-input v-model="temp.parameterValue" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="memo">
              <el-input v-model="temp.memo" type="textarea" :autosize="{ minRows: 2}" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用">
              <el-switch v-model="temp.status" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <!-- <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      height="200">

      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!disabled"
          type="primary"
          @click="dialogStatus==='create'?addData():updateData()">保存</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import {
  getListPage,
  saveOrUpdate,
  getTypes,
  deleteById
} from '@/api/dsc/system/config'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscConfig',
  mixins: [tableMixin],
  data() {
    return {
      test: [],
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {
        // 搜索条件
        keyName: '',
        parameterType: '',
        page: 1,
        size: 20
      },
      filterData: {
        parameterType: {
          key: 'parameterType',
          type: 'select',
          placeholder: '所有配置类型',
          title: '配置类型',
          options: [],
          props: {
            label: 'label',
            value: 'id'
          }
        },
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '名称、编号、描述'
        }
      },
      option: [], // 配置类型
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      total: 0,
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {
        // 弹窗表单
        id: null,
        parameterName: '',
        parameterCode: '',
        parameterValue: '',
        memo: '',
        status: true
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        parameterName: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }
        ],
        parameterType: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }
        ],
        parameterCode: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }
        ],
        parameterValue: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' }
        ],
        memo: [{ max: 255, message: '小于255个字符', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false // 是否禁止表单操作
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    getTypes({}).then(response => {
      this.option = Object.assign([], response.data)
      this.filterData['parameterType'].options = response.data.map(item => ({ label: item, id: item }))
      this.getListPage()
    })
  },
  methods: {
    // 查询列表
    getListPage() {
      this.listLoading = true
      getListPage(this.listQuery)
        .then(response => {
          this.tableData = response.data.records
          this.total = response.data.total
          for (const i of this.tableData) {
            i.status = !!i.status
          }
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 0 * 1000)
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getListPage()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      const param = Object.assign({}, params)
      param.status = param.status ? 1 : 0
      saveOrUpdate(param).then(response => {
        response.data.status = !!response.data.status
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          Object.assign(this.tableData[this.rowIndex], response.data)
        }
        if (!this.option.includes(response.data.parameterType)) {
          this.option.push(response.data.parameterType)
        }
        this.notifiySuccess('保存成功!')
        this.dialog.visible = false
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteById(row.id).then(response => {
            this.notifiySuccess('删除成功!')
            // this.tableData.splice($index, 1)
            // this.total--
            this.getListPage()
          })
        })
        .catch(() => {})
    },
    // 启用、停用
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    }
  }
}
</script>
